﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace IPCByMessages
{
    public class ServerMesagesChannel : MessagesChannelBase, IMessagesChannel
    {
        /// <summary>
        /// Setup server connection at specified port
        /// </summary>
        /// <param name="port">Port to connect</param>
        internal ServerMesagesChannel(int port)
        {
            try
            {
                connection = new Socket(AddressFamily.InterNetwork,
                    SocketType.Stream,
                    ProtocolType.Tcp);

                var adress = Dns.GetHostAddresses(Environment.MachineName)[0];
                var endPoint = new IPEndPoint(adress, port);

                connection.Bind(endPoint);
                connection.Listen(1);

                StartToAccept();
            }
            catch
            {
                Close();
                throw;
            }
        }

        #region Setup

        /// <summary>
        /// Start to accept incoming connections
        /// </summary>
        private void StartToAccept()
        {
            connection.BeginAccept(AcceptCallback, null);
        }

        /// <summary>
        /// Callback for incoming connection setup
        /// </summary>
        /// <param name="res">Result</param>
        private void AcceptCallback(IAsyncResult res)
        {
            otherSide = connection.EndAccept(res);
            Active = true;
            BeginReceive();
        }
        
        #endregion
    }
}
